package com.ddpt.platform.common.util.url;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.ddpt.platform.common.exception.CommonException;
import com.ddpt.platform.common.util.LoggerUtil;
import org.apache.commons.lang3.StringUtils;

/**
 * 长链转短链
 */
public class UrlChangeUtil {

    // 转短链
    public static ChangeUrlResp getChangeUrl(ChangeUrlReq req) {

        if (StringUtils.isBlank(req.getDomainAddress())) req.setDomainAddress("hmurl.cn");
        if (StringUtils.isBlank(req.getHandlerType())) req.setHandlerType("REDIRECT");
        String post = HttpUtil.post("http://hmurl.cn/short_url/add", JSONUtil.toJsonStr(req));

        LoggerUtil.info(UrlChangeUtil.class, "转断链结果为{}", post);

        if (StringUtils.isBlank(post)) return null;

        JSONObject jsonObject = JSONUtil.parseObj(post);
        if (jsonObject.getInt("status") != 200) throw new CommonException(jsonObject.getStr("message"));

        ChangeUrlResp resp = jsonObject.get("payload", ChangeUrlResp.class);

        if (resp != null && StringUtils.isNotBlank(resp.getDomainAddress()) && StringUtils.isNotBlank(resp.getShortUrl())) {
            resp.setReqUrl(req.getLongUrl().split(":")[0] + "://" + resp.getDomainAddress() + "/" + resp.getShortUrl());
        }

        return resp;
    }
}
